package com.zhou.JavaAndroidFirm.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhou.JavaAndroidFirm.R;
import com.zhou.JavaAndroidFirm.adapter.CircleAdapter;
import com.zhou.JavaAndroidFirm.app.AppToast;
import com.zhou.JavaAndroidFirm.base.BaseActivity;
import com.zhou.JavaAndroidFirm.bean.CircleItem;
import com.zhou.JavaAndroidFirm.bean.CommentItem;
import com.zhou.JavaAndroidFirm.bean.FavortItem;
import com.zhou.JavaAndroidFirm.bean.PageBean;
import com.zhou.JavaAndroidFirm.constract.CircleZoneContract;
import com.zhou.JavaAndroidFirm.constract.CommentConfig;
import com.zhou.JavaAndroidFirm.model.CircleZoneModel;
import com.zhou.JavaAndroidFirm.presenter.CircleZonePresenter;
import com.zhou.JavaAndroidFirm.utils.AppCache;
import com.zhou.JavaAndroidFirm.utils.DisplayUtil;
import com.zhou.JavaAndroidFirm.utils.KeyBordUtil;
import com.zhou.JavaAndroidFirm.widget.CommentListView;
import com.zhou.JavaAndroidFirm.widget.LoadingTip;
import com.zhou.JavaAndroidFirm.widget.NormalTitleBar;
import com.zhou.JavaAndroidFirm.widget.ZoneHeaderView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author Administrator
 * @date 2018/7/19 0019
 * @des 好友动态  类似朋友圈的效果
 */
public class CircleZoneActivity extends BaseActivity<CircleZonePresenter, CircleZoneModel> implements
        CircleZoneContract.View, OnRefreshListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.irc)
    ListView irc;
    @BindView(R.id.loadedTip)
    LoadingTip loadedTip;
    @BindView(R.id.fab1)
    FloatingActionButton fab1;
    @BindView(R.id.fab2)
    FloatingActionButton fab2;
    @BindView(R.id.fab3)
    FloatingActionButton fab3;
    @BindView(R.id.fab4)
    FloatingActionButton fab4;
    @BindView(R.id.fab5)
    FloatingActionButton fab5;
    @BindView(R.id.menu_red)
    FloatingActionMenu menuRed;
    @BindView(R.id.circleEt)
    EditText circleEt;
    @BindView(R.id.sendIv)
    ImageView sendIv;
    @BindView(R.id.editTextBodyLl)
    LinearLayout editTextBodyLl;
    //    @BindView(R.id.zoneHeaderView)
    ZoneHeaderView zoneHeaderView;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;

    private CircleAdapter mAdapter;
    private CommentConfig mCommentConfig;
    private int mScreenHeight;
    private int mEditTextBodyHeight;
    private int mCurrentKeyboardH;
    private int mSelectCircleItemH;
    private int mSelectCommentItemOffset;

    @Subscribe
    public void handleEvent(CircleItem circleItem) {
        if (circleItem != null) {
            this.setOnePublishData(circleItem);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fra_circle_list;
    }

    @Override
    protected void initPresenter() {
        mPresenter.onCreate(mModel, this);
    }


    @Override
    protected void doBeforeSetcontentView() {
        super.doBeforeSetcontentView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * @param bundle
     */
    @Override
    protected void initView(Bundle bundle) {
        menuRed.setClosedOnTouchOutside(true);
        ntb.setTitleText(mContext.getString(R.string.circle_zone));
        mAdapter = new CircleAdapter(mContext, mPresenter, new ArrayList<CircleItem>());
        //初始化头部未读消息
        zoneHeaderView = new ZoneHeaderView(mContext);
        zoneHeaderView.setData(getString(R.string.nick_name), AppCache.getInstance().getIcon());
        irc.addHeaderView(zoneHeaderView);
        irc.setAdapter(mAdapter);
        //滑动列表关闭输入框
        irc.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (editTextBodyLl.getVisibility() == View.VISIBLE)
                    updateEditTextBodyVisible(View.GONE, null);
                return false;
            }
        });

        refresh.setOnRefreshListener(this);
    }

    @Override
    protected void initEvent() {
        loadData();
    }

    private void loadData() {
        if (mAdapter.getPageBean().isRefresh()) {
            //刷新时刷新未读条数
            mPresenter.getNotReadNewsCount();
        }
        mPresenter.getListData(null, null, mAdapter.getPageBean().getLoadPage(), mAdapter.getPageBean().getRows());
    }

    public static void startAction(Context context) {
        Intent intent = new Intent(context, CircleZoneActivity.class);
        context.startActivity(intent);
    }


    @OnClick({R.id.tv_back, R.id.tv_right, R.id.sendIv, R.id.fab1, R.id.fab2, R.id.fab3, R.id.fab4, R.id.fab5, R.id.menu_red})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fab1:
            case R.id.fab2:
            case R.id.fab3:
            case R.id.fab4:
            case R.id.fab5:
                menuRed.close(true);
                CirclePublishActivity.startAction(this);
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.sendIv:
                if (mPresenter != null) {
                    //发布评论
                    String content = circleEt.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        AppToast.showToast("评论内容不能为空");
                        return;
                    }
                    mPresenter.addComment(content, mCommentConfig);
                }
                updateEditTextBodyVisible(View.GONE, null);
                break;
            default:
                break;
        }
    }

    @Override
    public void updateNotReadNewsCount(int count, String icon) {
        zoneHeaderView.setNotReadMsgData(count, icon);
    }

    @Override
    public void setListData(List<CircleItem> circleItems, PageBean pageBean) {
        if (refresh.isLoading()) {
            mAdapter.addAll(circleItems);
            refresh.finishLoadMore();
        } else {
            mAdapter.reset(circleItems);
            refresh.finishRefresh();
        }

        if (mAdapter.getItemCount() > 0) {
            loadedTip.setLoadingTip(LoadingTip.LoadStatus.finish);
        } else {
            loadedTip.setLoadingTip(LoadingTip.LoadStatus.empty);
        }

    }

    @Override
    public void setOnePublishData(CircleItem circleItem) {
        mAdapter.add(0, circleItem);
    }

    @Override
    public void update2DeleteCircle(String circleId, int position) {
        mAdapter.remove(position);
    }

    @Override
    public void update2AddFavorite(int circlePosition, FavortItem addItem) {
        if (addItem != null) {
            mAdapter.getData().get(circlePosition).getGoodjobs().add(addItem);
            mAdapter.notifyItemChanged(circlePosition, irc);
        }
    }

    @Override
    public void update2DeleteFavort(int circlePosition, String UserId) {
        List<FavortItem> items = mAdapter.getData().get(circlePosition).getGoodjobs();
        for (int i = 0; i < items.size(); i++) {
            if (UserId.equals(items.get(i).getUserId())) {
                items.remove(i);
                mAdapter.notifyItemChanged(circlePosition, irc);
                return;
            }
        }
    }

    @Override
    public void update2AddComment(int circlePosition, CommentItem addItem) {
        if (addItem != null) {
            mAdapter.getData().get(circlePosition).getReplys().add(addItem);
            mAdapter.notifyItemChanged(circlePosition, irc);
        }
        //清空评论文本
        circleEt.setText("");
    }


    @Override
    public void update2DeleteComment(int circlePosition, String commentId, int commentPosition) {
        List<CommentItem> items = mAdapter.getData().get(circlePosition).getReplys();
        items.remove(commentPosition);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void updateEditTextBodyVisible(int visibility, CommentConfig commentConfig) {
        mCommentConfig = commentConfig;
        editTextBodyLl.setVisibility(visibility);

        measureCircleItemHighAndCommentItemOffset(commentConfig);

        if (commentConfig != null && CommentConfig.Type.REPLY.equals(commentConfig.getCommentType())) {
            circleEt.setHint("回复" + commentConfig.getName() + ":");
        } else {
            circleEt.setHint("说点什么吧");
        }
        if (View.VISIBLE == visibility) {
            circleEt.requestFocus();
            //弹出键盘
            KeyBordUtil.showSoftKeyboard(circleEt);
            //隐藏菜单
            menuRed.hideMenuButton(true);
        } else if (View.GONE == visibility) {
            //隐藏键盘
            KeyBordUtil.hideSoftKeyboard(circleEt);
            //显示菜单
            menuRed.showMenuButton(true);
        }
    }

    private void measureCircleItemHighAndCommentItemOffset(CommentConfig commentConfig) {
        if (commentConfig == null)
            return;

        int headViewCount = irc.getHeaderViewsCount();
        //当前选中的view
        int selectPostion = commentConfig.circlePosition + headViewCount;
//        int selectPostion = commentConfig.circlePosition + headViewCount + 1;
        View selectCircleItem = irc.getChildAt(selectPostion - irc.getFirstVisiblePosition());

        if (selectCircleItem != null) {
            mSelectCircleItemH = selectCircleItem.getHeight() - DisplayUtil.dip2px(48);
            //获取评论view,计算出该view距离所属动态底部的距离
            if (commentConfig.commentType == CommentConfig.Type.REPLY) {
                //回复评论的情况
                CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList);
                if (commentLv != null) {
                    //找到要回复的评论view,计算出该view距离所属动态底部的距离
                    View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition);
                    if (selectCommentItem != null) {
                        //选择的commentItem距选择的CircleItem底部的距离
                        mSelectCommentItemOffset = 0;
                        View parentView = selectCommentItem;
                        do {
                            int subItemBottom = parentView.getBottom();
                            parentView = (View) parentView.getParent();
                            if (parentView != null) {
                                mSelectCommentItemOffset += (parentView.getHeight() - subItemBottom);
                            }
                        }
                        while (parentView != null && parentView != selectCircleItem);
                    }
                }
            }
        }
    }

    @Override
    public void startProgressDialog() {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.loading);
    }

    @Override
    public void stopProgressDialog() {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.finish);
    }

    @Override
    public void showTip(String tip) {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.error);
        loadedTip.setTips(tip);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (editTextBodyLl != null && editTextBodyLl.getVisibility() == View.VISIBLE) {
                editTextBodyLl.setVisibility(View.GONE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        loadData();
    }
}
